package com.socool.sinofaith.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Region {
	DBManager dbm;
	SQLiteDatabase db;
	public String getProvince(String province,Context context){
		try {
			dbm = new DBManager(context);
			dbm.openDatabase();
			db = dbm.getDatabase();
			if(null!=province){
				String sql = "select * from province";
				Cursor cursor = db.rawQuery(sql, null);
				cursor.moveToFirst();
				while (!cursor.isLast()) {
					String code = cursor.getString(cursor.getColumnIndex("code"));
					byte bytes[] = cursor.getBlob(2);
					String name = new String(bytes, "gbk");
					if(code.substring(0,2).equals(province)){
						province=name;
						break;
					}
					cursor.moveToNext();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			dbm.closeDatabase();
			db.close();
		}
		return province;
	}
	
	public String getCity(String city,Context context){
		try {
			dbm = new DBManager(context);
			dbm.openDatabase();
			db = dbm.getDatabase();
			if(null!=city){
				String sql = "select * from city";
				Cursor cursor = db.rawQuery(sql, null);
				cursor.moveToFirst();
				while (!cursor.isLast()) {
					String code = cursor.getString(cursor.getColumnIndex("code"));
					byte bytes[] = cursor.getBlob(2);
					String name = new String(bytes, "gbk");
					if(code.substring(0,4).equals(city)){
						city=name;
						break;
					}
					cursor.moveToNext();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			dbm.closeDatabase();
			db.close();
		}
		return city;
	}
	
	public String getCounty(String county,Context context){
		try {
			dbm = new DBManager(context);
			dbm.openDatabase();
			db = dbm.getDatabase();
			if(null!=county){
				String sql = "select * from district";
				Cursor cursor = db.rawQuery(sql, null);
				cursor.moveToFirst();
				while (!cursor.isLast()) {
					String code = cursor.getString(cursor.getColumnIndex("code"));
					byte bytes[] = cursor.getBlob(2);
					String name = new String(bytes, "gbk");
					if(code.equals(county)){
						county=name;
						break;
					}
					cursor.moveToNext();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			dbm.closeDatabase();
			db.close();
		}
		return county;
	}
}
